<template>
  <view class="detail-page">
	  <div class="top-img">
		  <!-- 左上角圆形回退键 -->
		  <view class="back-button" @click="handleBack">
			  <uni-icons size="28" color="#fff" type="left"></uni-icons>
		  </view>
		  <image class="img-box" mode="aspectFill" :src="recipeData.cover_image || '/static/images/02.jpg'" alt="" @error="onImageError" />
	  </div>
	  
	  <!-- 内容卡片容器 -->
	  <view class="card-container">
    <!-- 菜品基础信息 -->
    <view class="recipe-info-card">
      <view class="recipe-title-row">
          <text class="recipe-title">{{ recipeData.title }}</text>
          <view class="action-buttons">
            <view class="like-btn" @click="toggleLike">
              <uni-icons size="30" color="#ff6b6b" class="like-icon" :type="isLiked ? 'hand-up-filled' : 'hand-up'"/>
            </view>
            <view class="favorite-btn" @click="toggleFavorite">
              <uni-icons size="30" color="#ff6b6b" class="favorite-icon" :type="isFavorite ? 'star-filled' : 'star'"/>
            </view>
          </view>
        </view>

      <view class="recipe-meta">
        <view class="meta-item">
          <text class="meta-label">评分：</text>
          <text class="meta-value">{{ recipeData?.comments?.[0]?.rating || "暂无评" }}分</text>
        </view>
        <view class="meta-item">
          <text class="meta-label">难度：</text>
          <text class="meta-value">{{ recipeData.difficulty || "暂无数据" }}</text>
        </view>
        <view class="meta-item">
          <text class="meta-label">耗时：</text>
          <text class="meta-value">{{ recipeData.cook_time || "暂无数据" }}分钟</text>
        </view>
      </view>
		
	  <!-- 标签tags -->
      <view class="recipe-tags">
        <text
          class="tag-item"
          v-for="(tag, idx) in recipeData.tags"
          :key="idx"
        >{{ tag.name }}</text>
      </view>
    </view>

    <!-- 食材区域 -->
    <view class="ingredients-card">
      <view class="card-title">食材</view>
      <template v-if="groupedIngredients.length > 0">
        <view class="ingredient-group" v-for="(group, idx) in groupedIngredients" :key="idx">
          <view class="group-title">{{ group.title }}</view>
          <view class="ingredient-item" v-for="(item, itemIdx) in group.items" :key="itemIdx">
            <text class="ingredient-name">{{ item.name }}</text>
            <text class="ingredient-amount">{{ item.amount }}</text>
          </view>
        </view>
      </template>
      <template v-else>
        <view class="empty-ingredients">暂无食材数据</view>
      </template>
    </view>

	

    <!-- 步骤区域 -->
    <view class="steps-card">
      <view class="card-title">做法步骤</view>
      <template v-if="recipeData.steps && recipeData.steps.length > 0">
        <view class="step-item" v-for="(step, idx) in recipeData.steps" :key="idx">
          <view class="step-num">{{ idx + 1 }}</view>
          <view class="step-content">
            <text class="step-desc">{{ step.description }}</text>
          </view>
        </view>
      </template>
      <template v-else>
        <view class="empty-steps">暂无步骤数据</view>
      </template>
    </view>
    
  </view> <!-- 闭合card-container -->
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {onLoad} from "@dcloudio/uni-app"
import {getMenuDetail, likeRecipe, unlikeRecipe, favoriteRecipe, unfavoriteRecipe, checkLikeStatus, checkFavoriteStatus, getRecipeLikeCount, getRecipeFavoriteCount} from '/apis/index.js'

// 接收页面传的参数
onLoad((option)=>{
	apiID.value = option.id
})

// 页面开始加载数据
onMounted(()=>{
	// 先加载食材类别映射，再获取菜谱详情
	loadIngredientCategories().then(() => {
		getDetailData(apiID.value)
	})
})

// 获取食材类别映射（从后端或配置中）
const loadIngredientCategories = async() => {
  try {
    // 理想情况下，应该从后端API获取食材类别映射
    // const response = await getIngredientCategories();
    // ingredientCategories.value = response.data;
    
    // 目前使用备用方案：前端配置的类别映射
    ingredientCategories.value = {
      '1': '肉类',
      '2': '蔬菜',
      '3': '调料',
      '4': '主食',
      '5': '水果',
      '6': '水产',
      '7': '干货',
      '8': '乳制品',
      '9': '豆制品',
      '10': '蛋类',
      '11': '菌菇类',
      '12': '粉面类',
      '13': '油脂类'
    };
  } catch (error) {
    console.error('加载食材类别失败:', error);
    // 出错时使用默认映射
    ingredientCategories.value = {
      '1': '肉类',
      '2': '蔬菜',
      '3': '调料',
      '其他': '其他'
    };
  }
}

// 获取用户信息（从本地存储中获取）
function getUserInfo() {
  const userInfo = uni.getStorageSync('userInfo')
  if (userInfo) {
    return JSON.parse(userInfo)
  }
  return null
}

const getDetailData = async(id) =>{
	try {
		const data = await getMenuDetail(id)
		recipeData.value = data
		// 添加日志输出菜谱详细信息
		console.log('菜谱详细信息:', data);
		
		// 获取用户信息
		const userInfo = getUserInfo()
		if (userInfo && userInfo.id) {
			// 获取点赞和收藏状态
			await Promise.all([
				loadLikeStatus(userInfo.id, id),
				loadFavoriteStatus(userInfo.id, id)
			])
		}
	}catch (err) {
		// 静默处理错误
		console.error('获取菜谱详情失败:', err);
	}
}

// 加载点赞状态
async function loadLikeStatus(userId, recipeId) {
	try {
		// 转换recipe_id为整数
		const recipeIdInt = parseInt(recipeId)
		const result = await checkLikeStatus(userId, recipeIdInt)
		isLiked.value = result.is_liked || false
		likeId.value = result.like_id || null
	} catch (error) {
		isLiked.value = false
		likeId.value = null
	}
}

// 加载收藏状态
async function loadFavoriteStatus(userId, recipeId) {
	try {
		// 转换recipe_id为整数
		const recipeIdInt = parseInt(recipeId)
		const result = await checkFavoriteStatus(userId, recipeIdInt)
		isFavorite.value = result.is_favorited || false
		// 收藏状态检查接口不返回ID，只有在收藏时才会获取
		favoriteId.value = null
	} catch (error) {
		isFavorite.value = false
		favoriteId.value = null
	}
}

// 响应式数据
const apiID = ref()
const isFavorite = ref(false) // 收藏
const isLiked = ref(false) // 点赞
const recipeData = ref({})
const recipe = ref({})
const favoriteId = ref(null) // 收藏记录ID
const likeId = ref(null) // 点赞记录ID
const ingredientCategories = ref({}) // 食材类别映射

// 计算属性：将API返回的食材列表按类别分组
const groupedIngredients = computed(() => {
  if (!recipeData.value.ingredients || recipeData.value.ingredients.length === 0) {
    return []
  }
  
  // 按category字段分组
  const groups = {};
  recipeData.value.ingredients.forEach(item => {
    let category = item.ingredient?.category || '其他';
    // 如果category是数字，转换为对应的文字类别
    if (typeof category === 'string' && ingredientCategories.value[category]) {
      category = ingredientCategories.value[category];
    }
    if (!groups[category]) {
      groups[category] = []
    }
    // 处理小数显示问题，将2.00这样的小数转换为2
    const quantity = Number(item.quantity);
    const displayQuantity = quantity % 1 === 0 ? quantity.toString() : item.quantity;
    groups[category].push({
      name: item.ingredient?.name || '',
      amount: `${displayQuantity}${item.unit}`
    })
  })
  
  // 转换为数组格式
  return Object.keys(groups).map(category => ({
      title: category,
      items: groups[category]
    }))
  })

  // 计算属性
  const recipeImgs = computed(() => {
    return recipeData.value.cover_image ? [recipeData.value.cover_image] : []
  })

// 添加加载状态变量
const isFavoriteLoading = ref(false)
const isLikeLoading = ref(false)

// 方法
// 切换收藏状态
async function toggleFavorite() {
    // 防止重复点击
    if (isFavoriteLoading.value) {
      return
    }
    
    // 检查用户是否登录
    const userInfo = getUserInfo()
    if (!userInfo || !userInfo.id) {
      uni.showToast({ title: '请先登录', icon: 'none' });
      return
    }

    // 确保有菜谱ID
    if (!apiID.value) {
      console.error('没有获取到菜谱ID')
      uni.showToast({ title: '操作失败，请重试', icon: 'none' });
      return
    }

    // 转换recipe_id为整数
    const recipeIdInt = parseInt(apiID.value)
    
    // 验证菜谱ID是否为有效的正整数
    if (isNaN(recipeIdInt) || recipeIdInt < 1) {
      return
    }

    try {
      isFavoriteLoading.value = true
      
      if (isFavorite.value) {
        // 取消收藏
        const result = await unfavoriteRecipe(userInfo.id, recipeIdInt)
        
        // 检查操作是否成功 - 调整为适应原始response格式
        if (result && (result.status === 200 || typeof result === 'object')) {
          // 立即更新本地状态，确保UI及时响应
          isFavorite.value = false
          favoriteId.value = null
          uni.showToast({ title: '取消收藏成功', icon: 'success' });
        } else {
          throw new Error('取消收藏失败')
        }
      } else {
        // 收藏菜谱
        const result = await favoriteRecipe(userInfo.id, recipeIdInt)
        
        // 检查操作是否成功 - 调整为适应原始response格式
        if (result && (result.status === 200 || typeof result === 'object')) {
          // 立即更新本地状态，确保UI及时响应
          isFavorite.value = true
          // 尝试从响应中获取favorite_id
          if (result.data && result.data.favorite_id) {
            favoriteId.value = result.data.favorite_id
          }
          uni.showToast({ title: '收藏成功', icon: 'success' });
        } else {
          throw new Error('收藏失败')
        }
      }
      
      // 重新从服务器获取最新状态以确保数据一致性
      await loadFavoriteStatus(userInfo.id, recipeIdInt)
    } catch (error) {
      // 清除之前可能设置的状态，确保与服务器一致
      isFavorite.value = false
      favoriteId.value = null
      uni.showToast({ title: error.message || '操作失败，请重试', icon: 'none' });
      
      // 重新获取状态以确保前端显示与后端一致
      try {
        await loadFavoriteStatus(userInfo.id, recipeIdInt)
      } catch (reloadError) {
        console.error('重新加载收藏状态失败:', reloadError)
      }
    } finally {
      isFavoriteLoading.value = false
    }
  }

// 切换点赞状态
async function toggleLike() {
    // 防止重复点击
    if (isLikeLoading.value) {
      return
    }
    
    // 检查用户是否登录
    const userInfo = getUserInfo()
    if (!userInfo || !userInfo.id) {
      uni.showToast({ title: '请先登录', icon: 'none' });
      return
    }

    // 确保有菜谱ID
    if (!apiID.value) {
      console.error('没有获取到菜谱ID')
      uni.showToast({ title: '操作失败，请重试', icon: 'none' });
      return
    }

    // 转换recipe_id为整数
    const recipeIdInt = parseInt(apiID.value)
    
    // 验证菜谱ID是否为有效的正整数
    if (isNaN(recipeIdInt) || recipeIdInt < 1) {
      return
    }

    try {
      isLikeLoading.value = true
      
      if (isLiked.value) {
        // 取消点赞
        const result = await unlikeRecipe(likeId.value)
        
        // 检查操作是否成功 - 调整为适应原始response格式
        if (result && (result.status === 200 || typeof result === 'object')) {
          // 立即更新本地状态，确保UI及时响应
          isLiked.value = false
          likeId.value = null
          uni.showToast({ title: '取消点赞成功', icon: 'success' });
        } else {
          throw new Error('取消点赞失败')
        }
      } else {
        // 点赞
        const result = await likeRecipe(userInfo.id, recipeIdInt)
        
        // 检查操作是否成功 - 调整为适应原始response格式
        if (result && (result.status === 200 || typeof result === 'object')) {
          // 立即更新本地状态，确保UI及时响应
          isLiked.value = true
          // 尝试从响应中获取like_id，如果没有则在重新加载时获取
          if (result.data && result.data.like_id) {
            likeId.value = result.data.like_id
          }
          uni.showToast({ title: '点赞成功', icon: 'success' });
        } else {
          throw new Error('点赞失败')
        }
      }
      
      // 重新从服务器获取最新状态以确保数据一致性
      await loadLikeStatus(userInfo.id, recipeIdInt)
    } catch (error) {
      // 清除之前可能设置的状态，确保与服务器一致
      isLiked.value = false
      likeId.value = null
      uni.showToast({ title: error.message || '操作失败，请重试', icon: 'none' });
      
      // 重新获取状态以确保前端显示与后端一致
      try {
        await loadLikeStatus(userInfo.id, recipeIdInt)
      } catch (reloadError) {
        // 忽略重新加载失败的错误
      }
    } finally {
      isLikeLoading.value = false
    }
  }

// 图片加载失败处理函数
function onImageError(e) {
  // 设置默认图片路径
  e.target.src = '/static/images/02.jpg'
}

// 处理回退事件
function handleBack() {
  uni.switchTab({
  	url:'/pages/menu/menu'
  })
}
</script>

<style lang="scss" scoped>
.detail-page {
  background: linear-gradient(to bottom, #f9f9f9, #f1f8e9);
  min-height: 100vh;
  padding: 0;
  
  .top-img {
	  overflow: hidden;
	  position: relative;
	  height: 450rpx;
	  width: 100%;
	  
	  .back-button {
		  position: absolute;
		  top: 30rpx;
		  left: 30rpx;
		  width: 80rpx;
		  height: 80rpx;
		  border-radius: 50%;
		  background-color: rgba(0, 0, 0, 0.5);
		  display: flex;
		  justify-content: center;
		  align-items: center;
		  z-index: 10;
		  transition: all 0.3s ease;
	  }
	  
	  .back-button:active {
		  background-color: rgba(0, 0, 0, 0.7);
		  transform: scale(0.9);
	  }
	  
	  .img-box {
		  width: 100%;
		  height: 100%;
		  transition: transform 0.3s ease;
	  }
	  
	  .img-box:active {
		  transform: scale(1.02);
	  }
	  
	  // 添加渐变遮罩，增强文字可读性
	  &::after {
		  content: '';
		  position: absolute;
		  bottom: 0;
		  left: 0;
		  right: 0;
		  height: 150rpx;
		  background: linear-gradient(to top, rgba(0, 0, 0, 0.5), transparent);
	  }
  }
}

// 卡片容器，增加内边距
.card-container {
  padding: 20rpx;
  margin-top: -50rpx;
  position: relative;
  z-index: 1;
}

.recipe-info-card {
  background-color: #fff;
  border-radius: 24rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  border: 1px solid #e8f5e9;
}

.recipe-info-card:active {
  transform: translateY(-2rpx);
  box-shadow: 0 12rpx 24rpx rgba(0, 0, 0, 0.12);
}

.recipe-title-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.recipe-title {
  font-size: 38rpx;
  font-weight: bold;
  color: #ff6b6b;
  flex: 1;
  line-height: 52rpx;
  margin-right: 20rpx;
}

// 操作按钮容器
.action-buttons {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

// 收藏按钮样式
.favorite-btn {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 60rpx;
  height: auto;
  transition: all 0.3s ease;
}

.favorite-btn:active {
  transform: scale(0.9);
}

.favorite-icon {
  display: block;
  line-height: 1;
}

// 点赞按钮样式
.like-btn {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 60rpx;
  height: auto;
  transition: all 0.3s ease;
}

.like-btn:active {
  transform: scale(0.9);
}

.like-icon {
  display: block;
  line-height: 1;
}

.recipe-meta {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
  padding: 16rpx;
  background-color: #f1f8e9;
  border-radius: 12rpx;
}

.meta-item {
  margin-right: 30rpx;
  margin-bottom: 8rpx;
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #333;
}

.meta-label {
  font-weight: bold;
  color: #ff6b6b;
  margin-right: 6rpx;
}

.meta-value {
  color: #555;
}

.recipe-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.tag-item {
  background-color: #ff6b6b;
  color: #fff;
  padding: 8rpx 20rpx;
  border-radius: 24rpx;
  font-size: 22rpx;
  border: 1px solid #ff6b6b;
  transition: all 0.2s ease;
}

.tag-item:active {
  background-color: #ff5252;
  color: #fff;
  transform: scale(0.95);
}

// 食材卡片样式
.ingredients-card,
.steps-card {
  background-color: #fff;
  border-radius: 24rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  border: 1px solid #e8f5e9;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 20rpx;
  padding-bottom: 15rpx;
  border-bottom: 2px solid #f8f8f8;
  position: relative;
}

.card-title::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60rpx;
  height: 2px;
  background-color: #ff6b6b;
}

.ingredient-group {
  margin-bottom: 25rpx;
  padding: 16rpx;
  background-color: #fff5f5;
  border-radius: 16rpx;
  border-left: 4px solid #ff6b6b;
}

.group-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 15rpx;
  padding-left: 10rpx;
}

.ingredient-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 12rpx;
  padding: 8rpx 0;
  transition: all 0.2s ease;
}

.ingredient-item:active {
  transform: translateX(4rpx);
}

.ingredient-name {
  flex: 1;
  color: #333;
}

.ingredient-amount {
  color: #ff6b6b;
  font-weight: 500;
  background-color: #fff5f5;
  padding: 4rpx 16rpx;
  border-radius: 16rpx;
  font-size: 24rpx;
}

.empty-ingredients,
.empty-steps {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 160rpx;
  font-size: 28rpx;
  color: #999;
  text-align: center;
  background-color: #f8f8f8;
  border-radius: 16rpx;
  margin-top: 10rpx;
}

// 步骤样式优化
.step-item {
  display: flex;
  margin-top: 25rpx;
  padding-bottom: 25rpx;
  border-bottom: 1px dashed #e0e0e0;
  transition: all 0.2s ease;
}

.step-item:active {
  background-color: #fff5f5;
  border-radius: 16rpx;
  padding: 10rpx 0;
}

.step-item:last-child {
  border-bottom: none;
}

.step-num {
	background-color: #ff6b6b;
	color: white;
	width: 50rpx;
	height: 50rpx;
	border-radius: 50%;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 26rpx;
	font-weight: bold;
	margin-right: 20rpx;
	flex-shrink: 0;
	position: relative;
}

.step-num::after {
  content: '';
  position: absolute;
  top: 50rpx;
  left: 25rpx;
  width: 1px;
  height: calc(100% + 25rpx);
  background-color: #e0e0e0;
  z-index: 0;
}

.step-item:last-child .step-num::after {
  display: none;
}

.step-content {
  flex: 1;
  position: relative;
  z-index: 1;
}

.step-desc {
  font-size: 26rpx;
  color: #333;
  line-height: 44rpx;
  background-color: #fff5f5;
  padding: 16rpx 20rpx;
  border-radius: 12rpx;
  border-left: 3px solid #ff6b6b;
  // 添加自动换行样式
  white-space: normal;
  word-wrap: break-word;
  word-break: break-all;
  display: block;
}
</style>